package com.jsmile.cloud.goodscenter.web.mq.order;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.jsmile.cloud.tradecenter.api.enums.OrderStatusEnum;

import lombok.extern.slf4j.Slf4j;

/**
 * 订单状态变化策略
 */
@Service
@Slf4j
public class OrderStatusChangeStrategyMap implements ApplicationContextAware {

    private final Map<OrderStatusEnum, IOrderStatusStrategy> syncHandlerMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, IOrderStatusStrategy> beansOfTypeMap = applicationContext.getBeansOfType(IOrderStatusStrategy.class);
        if (!CollectionUtils.isEmpty(beansOfTypeMap)) {
            beansOfTypeMap.forEach((key, strategy) -> syncHandlerMap.putIfAbsent(strategy.orderStatus(), strategy));
        }
    }

    public IOrderStatusStrategy findStrategy(OrderStatusEnum orderStatus) {
        return syncHandlerMap.get(orderStatus);
    }

    public Optional<IOrderStatusStrategy> findStrategyOptional(OrderStatusEnum orderStatus) {
        return Optional.ofNullable(syncHandlerMap.get(orderStatus));
    }
}
